<template>
    <div class="plupload">
      <!-- 文本显示 -->
        <div v-if="displaymode == 'text'">
            <div style="width:100%" >

                <template v-for="item in initionData">
                    <div class="upload-item_text clearfix" :object = 'item.object'>
                        <div class="fl"><a class="tit" href="JavaScript:void(0);" :title="item.fileRealName">{{item.fileRealName}}</a></div>
                        <div class="fr">
                            <a class="text_link percent" href="JavaScript:void(0);" style="color:#67C23A"><i class="el-icon-circle-check"></i></a>
                            <a class="text_link" href="JavaScript:void(0);" @click="fileItemDelete(item.fileId,item.objectKey)">删除</a>
                            <a class="text_link" href="JavaScript:void(0);" @click="download(item.fileStoreName)">下载</a>
                        </div>
                    </div>
                </template>

                <template v-for="item in previewData">
                    <div class='upload-item_text clearfix' :id="item.fileId">
                        <div class="fl"><a class="tit" href="JavaScript:void(0);" :title="item.fileRealName">{{item.fileRealName}}</a></div>
                        <div class="fr">
                            <a class="text_link percent" href="JavaScript:void(0);"  v-if="item.percent != 100" style="color:#CCC">待上传</a>
                            <a class="text_link" href="JavaScript:void(0);" @click="fileItemDelete(item.fileId,item.objectKey)">删除</a>
                            <a class="text_link" href="JavaScript:void(0);" @click="download(item.fileStoreName)">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a>
                        </div>
                    </div>
                </template>
            </div>
        </div>
        <!-- 图片显示 -->
        <div v-if="displaymode == 'images'">
          <div style="width:100%">
            <template v-for="item in initionData">
              <div class='thumbnail upload-item' :object = 'item.object' onmouseover='$(this).find(".cover-show").slideDown(200);' onmouseleave='$(this).find(".cover-show").slideUp(200);'>
                <div class='cover-show'><span>{{item.fileRealName}}</span></div>
                <template v-if="item.isImage">
                  <img :src='item.fileStoreName' alt='' style='width:230px;height:140px;object-fit: cover;'>
                </template>
                <template v-else>
                  <img :src='item.previewImg' alt='' style='width:230px;height:140px;object-fit: cover;'>
                </template>

                <div class='caption'>
                  <div class='progress' style='visibility: hidden'><div class='progress-bar' style='width: 0%'></div></div>
                  <p> <el-button  size="small" type="danger" @click="fileItemDelete(item.fileId,item.objeobjectKeyct)">删除</el-button>&nbsp;&nbsp;
                    <el-button  size="small"  @click="download(item.fileStoreName)">下载</el-button>
                  </p>
                </div>
                <template v-if="!item.isImage">
                  <div  style='position: absolute;left:90px;top:60px;font-size: 20px;color:#fff'>{{item.fileType}}</div>
                </template>
              </div>
            </template>
          </div>
          <div style="width:100%" >
            <template v-for="item in previewData">
              <div class='thumbnail upload-item' :id="item.fileId" onmouseover='$(this).find(".cover-show").slideDown(200);' onmouseleave='$(this).find(".cover-show").slideUp(200);'>
                <div class='cover-show'><span>{{item.fileRealName}}</span></div>
                <img :src='item.fileStoreName' alt='' style='width:230px;height:140px;object-fit: cover;'>
                <div class='caption'>
                  <div class='progress'><div class='progress-bar' :style="{ 'width': 2*item.percent + '%' }" :aria-valuenow = "item.percent"></div></div>
                  <p> <el-button size="small" type="danger" @click="fileItemDelete(item.fileId,item.objectKey)">删除</el-button>&nbsp;<b class='percent'><span v-if="item.percent > 0">{{item.percent}}%</span></b></p>
                </div>
                <template v-if="!item.isImage">
                  <div  style='position: absolute;left:90px;top:60px;font-size: 20px;color:#fff'>{{item.fileType}}</div>
                </template>

              </div>
            </template>
          </div>
        </div>
          <div style="clear: both;"></div>
          <div :id="buttonIds.container">
            <el-button type="primary" size="mini" :id="buttonIds.select">选择文件</i></el-button>
            <el-button type="primary" size="mini" :id="buttonIds.upload">上传<i class="el-icon-upload el-icon--right"></i></el-button>
          </div>
    </div>
</template>


<script>
import PlUpload from "../../static/js/plupload/plupload.full.min";
import { get_upload_param } from "../../static/js/plupload/upparams";
import { config as appConfig } from "@/config.js";
export default {
  components: {
    PlUpload
  },
  data: function() {
    return {
      postData: [],
      previewData: [],  //  页面预显示数据
      uploader: {}, //上传对象
    };
  },
  watch: {
    initionData: function(val) {
      if (val && val.length > 0) {
        for (let i = 0; i < val.length; i++) {
          let item = this.initionData[i];
          this.initionData[i]["isImage"] = true;
          if (
            $.inArray(item.fileType, ["jpg", "jpeg", "gif", "png", "bmp"]) < 0
          ) {
            this.initionData[i]["isImage"] = false;
            this.initionData[i]["previewImg"] =
              "/static/js/plupload/suffix/otherfile.png";
          }
        }
        this.postData = this.initionData;
      }
    }
  },
  props: {
    initionData: {
      default: []
    },
    displaymode: {
      default: "images"
    },
    multiFile: {
      default: true
    },
    api: {
      default: true
    },
    imageOnly: {
      default: false
    },
    extensions: {
      default: ""
    },
    buttonIds: {
      default: function() {
        return {
          select: "selectfiles",
          upload: "postfiles",
          container: "container"
        };
      }
    }
  },
  methods: {
    previewImage: function(file, callback) {
      if (!/image\//.test(file.type)) {
        var name = file.name;
        var pos = name.lastIndexOf(".");
        var suffix = name.substring(pos + 1);
        callback && callback("/static/js/plupload/suffix/otherfile.png", suffix);
        return;
      }
      if (file.type == "image/gif") {
        //gif使用FileReader进行预览,因为mOxie.Image只支持jpg和png
        var fr = new mOxie.FileReader();
        fr.onload = function() {
          callback(fr.result, false);
          fr.destroy();
          fr = null;
        };
        fr.readAsDataURL(file.getSource());
      } else {
        var preloader = new mOxie.Image();
        preloader.onload = function() {
          preloader.downsize(300, 300); //先压缩一下要预览的图片,宽300，高300
          var imgsrc =
            preloader.type == "image/jpeg"
              ? preloader.getAsDataURL("image/jpeg", 80)
              : preloader.getAsDataURL(); //得到图片src,实质为一个base64编码的数据
          callback && callback(imgsrc, false); //callback传入的参数为预览图片的url
          preloader.destroy();
          preloader = null;
        };
        preloader.load(file.getSource());
      }
    },
    initFilters: function() {
      if (this.extensions) {
        return [{ title: "definedExtensions", extensions: this.extensions }];
      } else {
        let filters = [
          { title: "Image files", extensions: "jpg,jpeg,gif,png,bmp" }
        ];
        if (!this.imageOnly) {
          filters.push({ title: "Zip files", extensions: "zip,rar" });
          filters.push({
            title: "Doc files",
            extensions: "doc,xls,xlsx,docx,ppt,pptx,txt"
          });
          filters.push({ title: "video files", extensions: "mp4,avi,rmvb" });
        }
        return filters;
      }
    },
    // 设置某个特定的配置参数,option为参数名称
    setOption: function(up, file) {
      let self = this;
      //使用jquery的同步请求方式
      $.ajax({
        url:"http://47.104.3.233:8888/api/base/v1/getAliyunOSSSignature",
        type: "get",
        async: false, //使用同步的方式,true为异步方式
        headers: { Authorization: "Bearer "+localStorage.getItem(appConfig.TOKEN_KEY) }, //这里使用json对象
        success: function(data) {
          let params = get_upload_param(data, file.name);
          params["multipart_params"].Filename = self.api + '/' + params["multipart_params"].key;
          console.log('params["multipart_params"]');
          console.log(params["multipart_params"]);
          up.setOption({
            url: params["url"],
            multipart_params: params["multipart_params"]
          });
        }
      });
    },
    ossFileDelete: function(objectKey) {
      let self = this;
      self
        .axios({
          method: "post",
          url: self.axios.defaults.baseURL + "/upload/",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          transformRequest: [
            function(data) {
              let ret = "";
              for (let it in data) {
                ret +=
                  encodeURIComponent(it) +
                  "=" +
                  encodeURIComponent(data[it]) +
                  "&";
              }
              return ret;
            }
          ],
          data: { objectKey: objectKey }
        })
        .then(function(response) {
          if (response) {
            let result = response.data;
            if (result.success) {
              console.log(objectKey + "已删除");
            }
          }
        })
        .catch(function(err) {
          console.log("噢耶，报错咯");
        });
    },
    fileItemDelete: function(fileId, objectKey) {
      let self = this;
      if (fileId) {
        for (let i in self.uploader.files) {
          if (self.uploader.files[i].id === fileId) {
            self.uploader.files.splice(i, 1);
            break;
          }
        }

        for (let i in self.previewData) {
          if (self.previewData[i].fileId === fileId) {
            self.previewData.splice(i, 1);
            break;
          }
        }
      }
      if (objectKey) {
        let postParam = { objectKey: objectKey };
        self
          .$confirm("当前文件已上传完毕，确认要删除吗?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
          .then(() => {
            self
              .axios({
                method: "post",
                url: self.axios.defaults.baseURL + "/upload/",
                headers: {
                  "Content-Type": "application/x-www-form-urlencoded"
                },
                transformRequest: [
                  function(data) {
                    let ret = "";
                    for (let it in data) {
                      ret +=
                        encodeURIComponent(it) +
                        "=" +
                        encodeURIComponent(data[it]) +
                        "&";
                    }
                    return ret;
                  }
                ],
                data: postParam
              })
              .then(function(response) {
                if (response) {
                  let result = response.data;
                  if (result.success) {
                    for (let i = 0; i < self.postData.length; i++) {
                      if (objectKey == self.postData[i].objectKey) {
                        self.postData.splice(i, 1);
                        self.$emit("reloadFiles", self.postData);
                        break;
                      }
                    }
                  }
                }
              })
              .catch(function(err) {
                console.log("噢耶，报错咯");
              });
          })
          .catch(() => {
            self.$message({
              type: "info",
              message: "已取消删除"
            });
          });
      }
    },
    download: function(url) {
      window.open(url);
    },
    resetData:function(){
        if(this.uploader!=null){
          if(this.uploader.files!=null){
            this.uploader.splice(0,this.uploader.files.length)
            this.previewData=[];
          }

        }
    }
  },
  mounted: function() {
    let self= this;
    this.$nextTick(function() {

      self.uploader = new plupload.Uploader({
        runtimes: "html5,flash,silverlight,html4",
        browse_button: self.buttonIds.select,
        //multi_selection: false,
        container: document.getElementById(self.buttonIds.container),
        flash_swf_url: "../../static/js/plupload/Moxie.swf",
        silverlight_xap_url: "../../static/js/plupload/Moxie.xap",
        multi_selection: self.multiFile,
        url: "http://oss.aliyuncs.com",
        // multipart_params: {
        //     'Filename': '${filename}',
        //     'key' : '${filename}',
        //     'policy': policyBase64,
        //     'OSSAccessKeyId': accessid,
        //     'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
        //     'signature': signature,
        // },

        filters: {
          mime_types: this.initFilters(),
          max_file_size: "1000mb", //
          prevent_duplicates: true //不允许选取重复文件
        },
        // 初始化Plupload实例
        init: {
          PostInit: function() {
            document.getElementById(self.buttonIds.upload).onclick = function() {
              if (self.postData.length > 0 && !self.multiFile) {
                self.$confirm("确定替换已上传的文件吗?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                  })
                  .then(() => {
                    self.uploader.start();
                  })
                  .catch(() => {
                    self.$message({
                      type: "info",
                      message: "已取消上传"
                    });
                  });
              } else {
                self.uploader.start();
              }
              return false;
            };
          },

          FilesAdded: function(up, files) {
                console.log("fileStoreName");
            if (!self.multiFile) {
              // let file = _.cloneDeep(files.pop());
              let file = _.cloneDeep(files[0]);
              // let file = files[0];
              files = [];
              files.push(file);
              self.previewData = [];
            }
            plupload.each(files, function(file) {
              let data = {};
              data.fileRealName = file.name;
              data.fileId = file.id;
              data.isImage = true;
              data.percent = 0;
              self.previewImage(file, function(imgsrc, suffix) {
                // console.log(imgsrc);
                data.fileStoreName = imgsrc;
                if (suffix) {
                  data.isImage = false;
                  data.fileStoreName = imgsrc;
                  data.fileType = suffix;
                }
                self.previewData.push(data);
              });
            });
          },
        //  点击上传前
          BeforeUpload: function(up, file) {
            self.setOption(up, file);
          },
          //  点击上传后
          UploadProgress: function(up, file) {
            for (let i in self.previewData) {
              if (self.previewData[i].fileId === file.id) {
                self.previewData[i].percent = file.percent;
                break;
              }
            }
          },

          FileUploaded: function(up, file, info) {
            if (info.status == 200) {
              let data = new Object();
              let responseData = JSON.parse(info.response);
              console.log('responseData');
              console.log(responseData);
              if (responseData) {
                //完成上传后，如果只允许单个文件时，将其他已上传数据删除
                if (!self.multiFile) {
                  let each = self;
                  $.each(self.postData, function(i, item) {
                    each.ossFileDelete(item.object);
                  });
                  //清空要提交的数据
                  self.postData = [];
                }
                data.object = responseData.object;
                data.fileRealName = file.name;
                data.fileType = responseData.fileType;
                data.fileStoreName = responseData.fileStoreName;
                self.postData.push(data);
                self.$emit("reloadFiles", self.postData);
                self.fileItemDelete(file.id, null);
              } else {
                alert("上传数据回调异常");
              }
            } else if (info.status == 203) {

            } else {

            }
          },

          Error: function(up, err) {
            if (err.code == -600) {
              alert("文件大小超出限制");
            } else if (err.code == -601) {
              alert("文件类型不支持 ");
            } else if (err.code == -602) {
              alert("当前文件已经添加过了 ");
            } else {
              alert("文件上传签名超时了，请刷新页面重新选择");
            }
          }
        }
      });

      self.uploader.init();
    });
  }
};
</script>

<style>
.btn {
  color: #fff;
  background-color: #337ab7;
  border-color: #2e6da4;
  display: inline-block;
  padding: 6px 12px;
  margin-bottom: 0;
  font-size: 14px;
  font-weight: 400;
  line-height: 1.42857143;
  text-align: center;
  white-space: nowrap;
  text-decoration: none;
  vertical-align: middle;
  -ms-touch-action: manipulation;
  touch-action: manipulation;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  background-image: none;
  border: 1px solid transparent;
  border-radius: 4px;
  z-index: 0;
}

a.btn:hover {
  background-color: #3366b7;
}

.progress {
  margin-top: 2px;
  width: 200px;
  height: 14px;
  margin-bottom: 10px;
  overflow: hidden;
  background-color: #f5f5f5;
  border-radius: 4px;
  -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
  box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
}

.progress-bar {
  background-color: rgb(92, 184, 92);
  background-image: linear-gradient(
    45deg,
    rgba(255, 255, 255, 0.14902) 25%,
    transparent 25%,
    transparent 50%,
    rgba(255, 255, 255, 0.14902) 50%,
    rgba(255, 255, 255, 0.14902) 75%,
    transparent 75%,
    transparent
  );
  background-size: 40px 40px;
  box-shadow: rgba(0, 0, 0, 0.14902) 0px -1px 0px 0px inset;
  box-sizing: border-box;
  color: rgb(255, 255, 255);
  display: block;
  float: left;
  font-size: 12px;
  height: 20px;
  line-height: 20px;
  text-align: center;
  transition-delay: 0s;
  transition-duration: 0.6s;
  transition-property: width;
  transition-timing-function: ease;
  width: 266.188px;
}
.upload-item {
  margin-right: 15px;
  width: 230px;
  float: left;
  position: relative;
}

.cover-show {
  position: absolute;
  top: 0%;
  left: 0%;
  width: 100%;
  height: 140px;
  background-color: black;
  z-index: 1001;
  -moz-opacity: 0.7;
  opacity: 0.7;
  filter: alpha(opacity=70);
  text-align: center;
  display: none;
}
.cover-show span {
  color: #fff;
  font-size: 12px;
  line-height: 20px !important;
  word-wrap: break-word;
}
.upload-item_text{
    position: relative;
    margin-bottom: 3px;
}
.upload-item_text a {
  color: #5a5e66;
  font-size: 12px;
  line-height: 20px;
}
.upload-item_text a.tit {
  display: block;
  width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.upload-item_text .fl {
    width:100%;
    padding-right: 130px;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}
.upload-item_text .fr {
    position: absolute;
    right: 0;
    text-align: right;
    line-height: 24px;
    width: 130px;
    overflow: hidden;
}
.upload-item_text .fr a {
  color: #00bbbd;
  margin:0 3px;
}
.upload-item_text .percent{
    display: inline-block;
    width: 40px;
    text-align: center;
}
.plupload {
  padding-top: 10px;
}
</style>
